package com.dutiantech.partfastdfs.service;


import com.dutiantech.partfastdfs.config.ConfigUtil;
import com.dutiantech.partfastdfs.bean.FastdfsStorgeResult;
import com.dutiantech.partfastdfs.tools.UUIDUtils;
import com.dutiantech.rambo.tool.basic.DTDateUtil;
import com.dutiantech.rambo.tool.basic.DTStrUtil;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.InetSocketAddress;
import java.util.UUID;

/**
 * @author zhangly
 */

public class ImgProcessUtil
{
	/**
	 * Logger for this class
	 */
	private final static Logger logger = LoggerFactory.getLogger(ImgProcessUtil.class);


    private ConfigUtil configUtil;


	ImgProcessUtil( ConfigUtil configUtil){
		this.configUtil = configUtil;
	}
	void init() throws Exception {

		if(DTStrUtil.isNotEmpty(configUtil.tracker_server)){
			String[] szTrackerServers= configUtil.tracker_server.split(",");
			InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];
			for(int i = 0; i < szTrackerServers.length; ++i) {
				String[] parts = szTrackerServers[i].split("\\:", 2);
				if (parts.length != 2) {
					throw new Exception("the value of item \"tracker_server\" is invalid, the correct format is host:port");
				}
				tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
			}
			TrackerGroup g_tracker_group = new TrackerGroup(tracker_servers);
			ClientGlobal.setG_tracker_group(g_tracker_group);
		}else {
			throw new Exception("item \"tracker_server\" is not found");
		}
		ClientGlobal.setG_connect_timeout(configUtil.connect_timeout*1000);
		ClientGlobal.setG_anti_steal_token(configUtil.http_anti_steal_token);
		ClientGlobal.setG_charset(configUtil.charset);
		ClientGlobal.setG_network_timeout(configUtil.network_timeout*1000);
		ClientGlobal.setG_secret_key(configUtil.http_secret_key);
		ClientGlobal.setG_tracker_http_port(configUtil.http_tracker_http_port);
	}
    /**
     * 测试上传文档
     *
     * @throws Exception
     */
	/*public static IdcertImgParams imgUploadEncript(MultipartFile multipartFile, HttpServletRequest request, ImageEncrypt encrypt) throws Exception
	{
		logger.info("CONFIG_PATH = " +CONFIG_PATH);
		logger.info("GROUP_NAME = " +GROUP_NAME);
		if(null==encrypt){
			return imgUpload(multipartFile,request);
		}
		ClientGlobal.init(CONFIG_PATH);
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		StorageServer storageServer = null;
		StorageClient storageClient = new StorageClient(trackerServer, storageServer);

		byte[] fileBuffer = multipartFile.getBytes();

		//获取图片大小
		ByteArrayInputStream bis = new ByteArrayInputStream(fileBuffer);
		BufferedImage sourceImg = ImageIO.read(bis);
		ImageSize imgSize =  new ImageSize(sourceImg.getWidth(), sourceImg.getHeight());

		NameValuePair[] metadatas = new NameValuePair[3];

		// 这是文件的元数据(Metadata),基本上就是一个KV对,
		// 对于文件要存储的属性如文件类型,图片的长宽,自定义的文件名等可以这么放
		// 对于每个存在元数据的文档Storage会增加一个文件存放这些数据
		metadatas[0] = new NameValuePair("width", String.valueOf(imgSize.getWidth()));
		metadatas[1] = new NameValuePair("heigth", String.valueOf(imgSize.getHeight()));
		metadatas[2] = new NameValuePair("author", "netpaymgt");

		logger.info("file length: " + fileBuffer.length);

		StorageServer[] storageServers = trackerClient.getStoreStorages(trackerServer, GROUP_NAME);
		if (storageServers == null)
		{
			logger.info("get store storage servers fail, error code: " + storageClient.getErrorCode());
		} else
		{
			logger.info("store storage servers count: " + storageServers.length);

			// 这部分会打印storageServers
			for (int k = 0; k < storageServers.length; k++)
			{
				logger.info(k + 1 + ". " + storageServers[k].getInetSocketAddress().getAddress().getHostAddress() + ":"
						+ storageServers[k].getInetSocketAddress().getPort());
			}
			logger.info("---------------------------------------------");
		}

		long startTime = System.currentTimeMillis();

		// 上传文件,需要指定后缀,可以使用其他上传接口
		*//**
		 * 在这个进行图片加密
		 *//*
		fileBuffer =encrypt.encrypt(fileBuffer);

		*//**
		 * 加密结束
		 *//*



		String[] results = storageClient.upload_file(fileBuffer, "jpg", metadatas);

		logger.info("UPLOAD_FILE time used: " + (System.currentTimeMillis() - startTime) + " ms");

		if (results == null)
		{
			logger.info("upload file fail, error code: " + storageClient.getErrorCode());
			return null;
		}

		String groupName = results[0];
		String remoteFilename = results[1];
		logger.info("groupName: " + groupName + ", remoteFilename: " + remoteFilename);
		System.err.println(storageClient.get_file_info(groupName, remoteFilename));

		IdcertImgParams idcertImg = new IdcertImgParams();
		idcertImg.setUrl(remoteFilename);
		idcertImg.setWidth(imgSize.getWidth());
		idcertImg.setHeihgt(imgSize.getHeight());
		idcertImg.setFileLength(multipartFile.getSize());
		String id = UUIDUtils.getUuid();
		idcertImg.setId(id);

		return idcertImg;
	}

*/



    public  FastdfsStorgeResult imgUpload(MultipartFile multipartFile,String file_ext_name,String sys) throws Exception {


        byte[] fileBuffer = multipartFile.getBytes();
		return upFileByBytes(multipartFile.getSize(),fileBuffer,file_ext_name,sys);
	}

	public  FastdfsStorgeResult upFileByBytes(long multipartFileSize,  byte[] fileBuffer,String file_ext_name,String sys) throws Exception {
		//获取图片大小
		init();
		TrackerClient trackerClient = new TrackerClient();
		TrackerServer trackerServer = trackerClient.getConnection();
		StorageServer storageServer = null;
		StorageClient storageClient = new StorageClient(trackerServer, storageServer);
		//ByteArrayInputStream bis = new ByteArrayInputStream(fileBuffer);
	/*	BufferedImage sourceImg = ImageIO.read(bis);
		ImageSize imgSize =  new ImageSize(sourceImg.getWidth(), sourceImg.getHeight());
*/
		NameValuePair[] metadatas = new NameValuePair[3];

		// 这是文件的元数据(Metadata),基本上就是一个KV对,
		// 对于文件要存储的属性如文件类型,图片的长宽,自定义的文件名等可以这么放
		// 对于每个存在元数据的文档Storage会增加一个文件存放这些数据
		metadatas[0] = new NameValuePair("file_ext_name", file_ext_name);
		metadatas[1] = new NameValuePair("useSystem", sys);
		metadatas[2] = new NameValuePair("author", sys);

		logger.info("file length: " + fileBuffer.length);

		StorageServer[] storageServers = trackerClient.getStoreStorages(trackerServer, configUtil.group_name);
		if (storageServers == null)
        {
            logger.info("get store storage servers fail, error code: " + storageClient.getErrorCode());
        } else
        {
            logger.info("store storage servers count: " + storageServers.length);

            // 这部分会打印storageServers
            for (int k = 0; k < storageServers.length; k++)
            {
                logger.info(k + 1 + ". " + storageServers[k].getInetSocketAddress().getAddress().getHostAddress() + ":"
                        + storageServers[k].getInetSocketAddress().getPort());
            }
            logger.info("---------------------------------------------");
        }

		long startTime = System.currentTimeMillis();

		// 上传文件,需要指定后缀,可以使用其他上传接口
		/**
		 * 在这个进行图片加密
		 */


		String[] results = storageClient.upload_file(fileBuffer, file_ext_name, metadatas);
		logger.info("UPLOAD_FILE time used: " + (System.currentTimeMillis() - startTime) + " ms");

		if (results == null)
        {
            logger.info("upload file fail, error code: " + storageClient.getErrorCode());
            return null;
        }

		String groupName = results[0];
		String remoteFilename = results[1];
		logger.info("groupName: " + groupName + ", remoteFilename: " + remoteFilename);
		System.err.println(storageClient.get_file_info(groupName, remoteFilename));

		FastdfsStorgeResult idcertImg = new FastdfsStorgeResult();
		idcertImg.setUrl(remoteFilename);
		idcertImg.setSys(sys);
		idcertImg.setType(file_ext_name);
		idcertImg.setFileLength(multipartFileSize);
		String id = UUIDUtils.getUuid();
		idcertImg.setId(id);

		return idcertImg;
	}

	/**
	 * 返回文件大小
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public  long getFileLength(String path) throws Exception
	{
		File srcDir = new File(path);
		return srcDir.length();
	}

	/**
	 * 获得图片大小
	 *
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public  ImageSize getImageSize(String path) throws Exception
	{
		File picture = new File(path);
		BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
		return new ImageSize(sourceImg.getWidth(), sourceImg.getHeight());
	}

	/**
	 * @author QCC
	 *
	 */
	public  class ImageSize implements Serializable
	{
		private static final long serialVersionUID = 1L;
		int width;
		int height;

		public ImageSize()
		{

		}

		public ImageSize(int w, int h)
		{
			this.height = h;
			this.width = w;
		}

		public int getWidth()
		{
			return width;
		}

		public void setWidth(int width)
		{
			this.width = width;
		}

		public int getHeight()
		{
			return height;
		}

		public void setHeight(int height)
		{
			this.height = height;
		}

	}

	public  String generateImgUrl(MultipartFile certImg, HttpServletRequest request, long acctId, String imgPath)
			throws Exception
	{
		logger.info("netpay-web >>> generateImgUrl - start"); //$NON-NLS-1$
		logger.info("netpay-web >>> generateImgUrl para is: [acctId]" + acctId + "[imgPath]" + imgPath);
		String sep = System.getProperty("file.separator");
		String basePath = request.getSession().getServletContext().getRealPath("/") + imgPath;

		String time = DTDateUtil.getNowDateTime();
		String path = basePath + sep + time + sep + acctId; // 组织目录结构
		if (logger.isInfoEnabled())
		{
			logger.info("upload certImg path is:" + path);
		}
		byte[] bytes = certImg.getBytes();
		if (bytes.length != 0)
		{// 上传图片内容不为空

			File dirPath = new File(path);
			if (!dirPath.exists())
			{
				dirPath.mkdirs();
			}
			String fileTrueName = getFileName(certImg);
			String filePath = dirPath + sep + fileTrueName;

			String[] subFilePath = filePath.split("upload");
			String imgUrl = imgPath + subFilePath[1];
			imgUrl = imgUrl.replace("\\", "//");
			if (logger.isInfoEnabled())
			{
				logger.info("upload certImg all path is:" + filePath);
				logger.info("FileUrl is:" + imgUrl);
			}
			File uploadedFile = new File(filePath);
			FileCopyUtils.copy(bytes, uploadedFile);

			logger.info("netpay-web >>> generateImgUrl - end and imgUrl is:" + imgUrl); //$NON-NLS-1$
			return imgUrl;
		}
		logger.info("netpay-web >>> generateImgUrl - end but err !!!"); //$NON-NLS-1$
		return "";
	}
	public byte[]  downImg(String path) throws Exception {
		 //path="M00/00/28/wKhYbFnAeK-AZjMHAADRhc4GlsQ123.jpg";
       logger.info("netpay-web >>>  downImg - start"); //$NON-NLS-1$
		init();
       //ClientGlobal.init(CONFIG_PATH); // 初始化
       TrackerClient trackerClient = new TrackerClient();
       TrackerServer trackerServer = trackerClient.getConnection(); // 获取连接

       StorageClient storageClient = new StorageClient(trackerServer, null);

       byte[] imgBytes = storageClient.download_file(configUtil.group_name, path); // 访问文件服务器文件流
       
       return imgBytes;
   }
	

	
	
	private  String getFileName(MultipartFile fileData)
	{
		// 上传的文件名
		String uploadFileName = fileData.getOriginalFilename();

		String ext = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1, uploadFileName.length());
		ext = ext.toLowerCase(); // 后缀名称

		String uuid = UUID.randomUUID().toString();
		String imgName = uuid.replace("-", "");
		return imgName + "." + ext;
	}
}
